/*
 * Copyright 2002-2021 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.springframework.transaction.interceptor;

import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import org.springframework.aop.support.AopUtils;
import org.springframework.context.EmbeddedValueResolverAware;
import org.springframework.core.MethodClassKey;
import org.springframework.lang.Nullable;
import org.springframework.util.ClassUtils;
import org.springframework.util.StringValueResolver;

/**
 * Abstract implementation of {@link TransactionAttributeSource} that caches
 * attributes for methods and implements a fallback policy: 1. specific target
 * method; 2. target class; 3. declaring method; 4. declaring class/interface.
 * <br> TransactionAttributeSource 的实现抽象类，该类缓存了方法的属性并实现了回退策略：
 * 1. 特定目标方法;
 * 2. 目标类;
 * 3. 声明方法;
 * 4. 声明类/接口。
 * <br> 默认情况下，如果目标方法没有关联的事务属性，则使用目标类的事务属性。
 *
 * <p>Defaults to using the target class's transaction attribute if none is
 * associated with the target method. Any transaction attribute associated with
 * the target method completely overrides a class transaction attribute.
 * If none found on the target class, the interface that the invoked method
 * has been called through (in case of a JDK proxy) will be checked.
 * <br> 如果目标方法没有关联的事务属性，则默认使用目标类的事务属性。
 * 关联目标方法的事务属性完全覆盖类事务属性。
 * 如果目标类上没有找到事务属性，将检查通过其调用的方法所在的接口（在JDK代理的情况下）。
 *
 * <p>This implementation caches attributes by method after they are first used.
 * If it is ever desirable to allow dynamic changing of transaction attributes
 * (which is very unlikely), caching could be made configurable. Caching is
 * desirable because of the cost of evaluating rollback rules.
 * <br> 该实现通过首次使用后缓存属性。 如果将来需要允许动态更改事务属性（这几乎不可能），
 * 则缓存可以是可配置的。 由于评估回滚规则的成本，缓存是可取的。
 *
 * @author Rod Johnson
 * @author Juergen Hoeller
 * @since 1.1
 */
public abstract class AbstractFallbackTransactionAttributeSource
		implements TransactionAttributeSource, EmbeddedValueResolverAware {

	/**
	 * Canonical value held in cache to indicate no transaction attribute was
	 * found for this method, and we don't need to look again.
	 */
	@SuppressWarnings("serial")
	private static final TransactionAttribute NULL_TRANSACTION_ATTRIBUTE = new DefaultTransactionAttribute() {
		@Override
		public String toString() {
			return "null";
		}
	};


	/**
	 * Logger available to subclasses.
	 * <p>As this base class is not marked Serializable, the logger will be recreated
	 * after serialization - provided that the concrete subclass is Serializable.
	 */
	protected final Log logger = LogFactory.getLog(getClass());

	@Nullable
	private transient StringValueResolver embeddedValueResolver;

	/**
	 * Cache of TransactionAttributes, keyed by method on a specific target class.
	 * <br> TransactionAttributes 缓存，key= MethodClassKey(Method, Class),value=TransactionAttribute
	 * <p>As this base class is not marked Serializable, the cache will be recreated
	 * after serialization - provided that the concrete subclass is Serializable.
	 * <br> 由于 这个基类没有被标记为Serializable，缓存将在序列化后重新创建 - 前提是具体子类是可序列化的。
	 */
	private final Map<Object, TransactionAttribute> attributeCache = new ConcurrentHashMap<>(1024);

	/**
	 * 设置内嵌的属性解析器
	 * @param resolver
	 */
	@Override
	public void setEmbeddedValueResolver(StringValueResolver resolver) {
		this.embeddedValueResolver = resolver;
	}


	/**
	 * <p>
	 *     该函数getTransactionAttribute用于确定当前方法调用的事务属性。
	 *     1)首先，它检查方法是否属于Object类，如果是则返回null。
	 *     2)接着，它尝试从缓存中获取事务属性，如果缓存中存在则直接返回缓存值。
	 *     3)如果缓存中不存在，则通过computeTransactionAttribute方法计算事务属性，并将其放入缓存中。
	 *     4)如果计算得到的事务属性为null，则将NULL_TRANSACTION_ATTRIBUTE放入缓存；
	 *     5)否则，将事务属性及其方法标识符放入缓存，并返回该事务属性。
	 *     该函数在Spring框架中用于处理事务管理，确保方法调用时能够正确地应用事务属性，从而提高事务管理的效率和准确性。
	 *     在具体业务场景中，该函数被多个测试和事务管理相关的函数调用，用于验证事务属性的正确性和处理事务的逻辑。
	 * </p>
	 * Determine the transaction attribute for this method invocation.
	 * <p>Defaults to the class's transaction attribute if no method attribute is found.
	 * @param method the method for the current invocation (never {@code null})
	 * @param targetClass the target class for this invocation (may be {@code null})
	 * @return a TransactionAttribute for this method, or {@code null} if the method
	 * is not transactional
	 */
	@Override
	@Nullable
	public TransactionAttribute getTransactionAttribute(Method method, @Nullable Class<?> targetClass) {
		if (method.getDeclaringClass() == Object.class) {
			return null;
		}

		// First, see if we have a cached value.
		// 先查看是否有缓存值。
		Object cacheKey = getCacheKey(method, targetClass);
		TransactionAttribute cached = this.attributeCache.get(cacheKey);
		if (cached != null) {
			// Value will either be canonical value indicating there is no transaction attribute,
			// or an actual transaction attribute.
			// 值将是表示没有事务属性的规范值，或者实际的交易属性。
			if (cached == NULL_TRANSACTION_ATTRIBUTE) {
				return null;
			}
			else {
				return cached;
			}
		}
		else {
			// We need to work it out.
			//根据 Method,targetClass 计算 TransactionAttribute, 并将其放入缓存中。
			TransactionAttribute txAttr = computeTransactionAttribute(method, targetClass);
			// Put it in the cache.
			if (txAttr == null) {
				this.attributeCache.put(cacheKey, NULL_TRANSACTION_ATTRIBUTE);
			}
			else {
				//获取方法的全限定名（class全类名.方法名），并将其设置为 TransactionAttribute 的描述符。
				String methodIdentification = ClassUtils.getQualifiedMethodName(method, targetClass);
				if (txAttr instanceof DefaultTransactionAttribute dta) {
					dta.setDescriptor(methodIdentification);
					dta.resolveAttributeStrings(this.embeddedValueResolver);
				}
				if (logger.isTraceEnabled()) {
					logger.trace("Adding transactional method '" + methodIdentification + "' with attribute: " + txAttr);
				}
				this.attributeCache.put(cacheKey, txAttr);
			}
			return txAttr;
		}
	}

	/**
	 * Determine a cache key for the given method and target class.
	 * <p>Must not produce same key for overloaded methods.
	 * Must produce same key for different instances of the same method.
	 * @param method the method (never {@code null})
	 * @param targetClass the target class (may be {@code null})
	 * @return the cache key (never {@code null})
	 */
	protected Object getCacheKey(Method method, @Nullable Class<?> targetClass) {
		return new MethodClassKey(method, targetClass);
	}

	/**
	 * <p>
	 *     该函数computeTransactionAttribute用于计算给定方法和目标类的事务属性，而不缓存结果。
	 *     它的主要作用是通过分析方法和目标类来确定事务属性，确保事务的正确应用。
	 *     1) 首先，函数检查方法是否为公共方法，如果配置为仅允许公共方法且方法非公共，则返回null。
	 *     2) 接着，函数通过AopUtils.getMostSpecificMethod获取目标类中的具体方法。
	 *     3) 然后，函数尝试从该方法中查找事务属性，如果找到则返回。
	 *     4) 如果未找到，则尝试从目标类中查找事务属性，并检查是否为用户级别的方法。
	 *     5) 如果仍未找到，函数会回退到原始方法及其声明类中查找事务属性。
	 *     6) 最后，如果所有尝试都未找到事务属性，则返回null。
	 *     7) 该函数在Spring框架中用于动态确定事务属性，确保事务管理的灵活性和正确性。
	 * </p>
	 * Same signature as {@link #getTransactionAttribute}, but doesn't cache the result.
	 * {@link #getTransactionAttribute} is effectively a caching decorator for this method.
	 *
	 * <p>As of 4.1.8, this method can be overridden.
	 * @since 4.1.8
	 * @see #getTransactionAttribute
	 */
	@Nullable
	protected TransactionAttribute computeTransactionAttribute(Method method, @Nullable Class<?> targetClass) {
		// Don't allow non-public methods, as configured.
		if (allowPublicMethodsOnly() && !Modifier.isPublic(method.getModifiers())) {
			return null;
		}

		// The method may be on an interface, but we need attributes from the target class.
		// If the target class is null, the method will be unchanged.
		//1、method 可能是在接口上，但是我们需要从目标类中获取属性。如果目标类为空，则方法将保持不变。
		Method specificMethod = AopUtils.getMostSpecificMethod(method, targetClass);

		// First try is the method in the target class.
		//2、根据 method 获取 TransactionAttribute
		TransactionAttribute txAttr = findTransactionAttribute(specificMethod);
		if (txAttr != null) {
			return txAttr;
		}

		// Second try is the transaction attribute on the target class.
		//3、根据 targetClass 获取 TransactionAttribute
		txAttr = findTransactionAttribute(specificMethod.getDeclaringClass());
		if (txAttr != null && ClassUtils.isUserLevelMethod(method)) {
			return txAttr;
		}

		if (specificMethod != method) {
			// Fallback is to look at the original method.
			//3、传入的 method 和 specificMethod 不相同，尝试从原始的 method 中获取 TransactionAttribute
			txAttr = findTransactionAttribute(method);
			if (txAttr != null) {
				return txAttr;
			}
			// Last fallback is the class of the original method.
			//4、如果 specificMethod 和 method 不同，且从 原始的method也获取不到 事务属性，则尝试从原始的 method 的声明类中获取 TransactionAttribute
			txAttr = findTransactionAttribute(method.getDeclaringClass());
			if (txAttr != null && ClassUtils.isUserLevelMethod(method)) {
				return txAttr;
			}
		}

		return null;
	}


	/**
	 * Subclasses need to implement this to return the transaction attribute for the
	 * given class, if any.
	 * @param clazz the class to retrieve the attribute for
	 * @return all transaction attribute associated with this class, or {@code null} if none
	 */
	@Nullable
	protected abstract TransactionAttribute findTransactionAttribute(Class<?> clazz);

	/**
	 * Subclasses need to implement this to return the transaction attribute for the
	 * given method, if any.
	 * @param method the method to retrieve the attribute for
	 * @return all transaction attribute associated with this method, or {@code null} if none
	 */
	@Nullable
	protected abstract TransactionAttribute findTransactionAttribute(Method method);

	/**
	 * Should only public methods be allowed to have transactional semantics?
	 * <p>The default implementation returns {@code false}.
	 */
	protected boolean allowPublicMethodsOnly() {
		return false;
	}

}
